import pagejson from '../../package.json'
import formula from '@/constant/formula.json'
import color from 'css-color-function'
import rgbHex from 'rgb-hex'
import axios from 'axios'

// 生成新的样式表
export const createNewStyle = async (primary) => {
  let resp = await getStyles()
  const themeColor = getRstyle(primary)
  for (const key in themeColor) {
    resp = resp.replaceAll(key, themeColor[key])
  }
  const style = document.createElement('style')
  style.innerText = resp
  document.head.appendChild(style)
}
// 获取样式表替换标记
export const getRstyle = (primary) => {
  const colorObj = {}
  for (const key in formula) {
    const colors = formula[key].replaceAll('primary', primary)
    colorObj[key] = '#' + rgbHex(color.convert(colors))
  }
  const reColor = colorObj
  return reColor
}
// 得到element-plus样式表
const getStyles = async () => {
  const version = pagejson.dependencies['element-plus'].replace('^', '')
  const url = `https://unpkg.com/element-plus@${version}/dist/index.css`
  const resp = await axios.get(url)
  const styles = resp.data
  return getStyleTemplate(styles)
}

// 得到标记完的样式表
function getStyleTemplate(styles) {
  const colorMap = {
    '#3a8ee6': 'shade-1-t',
    '#409eff': 'primary-t',
    '#53a8ff': 'light-1-t',
    '#66b1ff': 'light-2-t',
    '#79bbff': 'light-3-t',
    '#8cc5ff': 'light-4-t',
    '#a0cfff': 'light-5-t',
    '#b3d8ff': 'light-6-t',
    '#c6e2ff': 'light-7-t',
    '#d9ecff': 'light-8-t',
    '#ecf5ff': 'light-9-t'
  }
  for (const key in colorMap) {
    styles = styles.replaceAll(key, colorMap[key])
  }
  return styles
}
